package org.teremail.panto.perf;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import junit.framework.TestCase;

import org.apache.james.mime4j.MimeException;
import org.apache.james.mime4j.parser.MimeStreamParser;
import org.teremail.panto.MimeParser;
import org.teremail.panto.ParseException;



public class PerformanceTestCase extends TestCase {

    final static int size = 2000;
    
    private void timeMime4J(String file) throws IOException, MimeException {
        long t0 = System.currentTimeMillis();
        for (int i = 0; i < size; i++) {
            InputStream fIn = new BufferedInputStream(new FileInputStream(file));
            MimeStreamParser p = new MimeStreamParser();
            p.setContentHandler(new Mime4JContentHandler());
            p.parse(fIn);
        }
        long t1 = System.currentTimeMillis();
        long time = t1 - t0;
        double mean = (double) time/(double) size;
        System.out.printf("Mime4J Time: %d, iterations: %d average: %f\n", t1-t0, size, mean);
    }
    
    private void timePanto(String file) throws IOException, ParseException {
        long t0 = System.currentTimeMillis();
        for (int i = 0; i < size; i++) {
            FileInputStream fIn = new FileInputStream(file);
            MimeParser p = new MimeParser();
            p.setContentHandler(new PantoContentHandler());
            p.parse(fIn);
        }
        long t1 = System.currentTimeMillis();
        long time = t1 - t0;
        double mean = (double) time/(double) size;
        System.out.printf("Panto Time: %d, iterations: %d average: %f\n", t1-t0, size, mean);
    }
    
    public void testLargePanto() throws Exception {
        timePanto("src/test/resources/test2.eml");
    }
    
    public void testLargeMime4J() throws Exception {
        timeMime4J("src/test/resources/test2.eml");
    }
    
    public void testNested() throws Exception {
        timeMime4J("src/test/resources/m-attachment-image.msg");
        timePanto("src/test/resources/m-attachment-image.msg");
    }
    
    public static int count(InputStream in) throws IOException {
        byte[] b = new byte[8192];
        int read = 0;
        for (int numRead = 0; (numRead = in.read(b)) != -1;) {
            read += numRead;
        }
        return read;
    }
    
}
